package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.TradePaymentWindowBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_7_trade_payment_suc_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_7_trade_payment_suc_window().init(
                5007,
                3,
                "DwsApp_7_trade_payment_suc_window",
                Constant.TOPIC_DWD_TRADE_PAY_DETAIL_SUC
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 过滤数据，封装为POJO
        SingleOutputStreamOperator<TradePaymentWindowBean> beanDs = toTradePaymentWindowBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> resultDs = windowAndAgg(beanDs);
        // 3 将结果写入Clickhouse
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_PAYMENT_SUC_WINDOW,TradePaymentWindowBean.class));
    }

    private SingleOutputStreamOperator<TradePaymentWindowBean> windowAndAgg(SingleOutputStreamOperator<TradePaymentWindowBean> ds) {
        // 1 创建水印
        WatermarkStrategy<TradePaymentWindowBean> strategy = WatermarkStrategy.<TradePaymentWindowBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean t1, TradePaymentWindowBean t2) throws Exception {
                        t2.setPaymentSucUniqueUserCount(t2.getPaymentSucUniqueUserCount() + t1.getPaymentSucUniqueUserCount());
                        t2.setPaymentSucNewUserCount(t2.getPaymentSucNewUserCount() + t1.getPaymentSucNewUserCount());
                        return t2;
                    }
                }, new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TradePaymentWindowBean> toTradePaymentWindowBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
//                .filter(j -> j.getString("user_id") != null)
                .keyBy(j -> j.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {

                    private ValueState<String> flagDate;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagDate = getRuntimeContext().getState(new ValueStateDescriptor<String>("flagDate", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>.Context ctx, Collector<TradePaymentWindowBean> out) throws Exception {
                        long ts = value.getLong("ts") * 1000;
                        String currentDate = TimeUtil.parseDateStr(ts, false);
                        long uuCt = 0L;
                        long nuCt = 0L;
                        if (!currentDate.equals(flagDate.value())){
                            uuCt = 1L;
                            if (flagDate.value() == null){
                                nuCt = 1L;
                            }
                            flagDate.update(currentDate);
                        }
                        if (uuCt == 1){
                            out.collect(
                                    TradePaymentWindowBean.builder()
                                            .paymentSucUniqueUserCount(uuCt)
                                            .paymentSucNewUserCount(nuCt)
                                            .ts(ts)
                                            .build()
                            );
                        }
                    }
                });
    }
}
